import 'package:async/async.dart';
import 'package:boss/color_constant.dart';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/reportForm/profitForm/page/interest_report_form_details.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flustars/flustars.dart' as flustars;

class InterestReportForm extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<InterestReportForm> {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  RefreshController _refreshController;

  DateTime startTime;

  DateTime endTime;

  List<dynamic> acceptData = [];

  int totalPercentageAmount = 0;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);

    final now = DateTime.now();

    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  refresh({bool needMove = true}) async {
    await _refreshController.requestRefresh(
      needMove: needMove,
      duration: Duration(milliseconds: 100),
    );
  }

  Widget titleBlock() {
    return Container(
      height: 172.w,
      decoration: BoxDecoration(
        gradient: const LinearGradient(colors: [
          Color.fromRGBO(85, 106, 246, .8),
          Color.fromRGBO(85, 106, 246, .7),
          Color.fromRGBO(85, 106, 246, .6),
        ]),
        borderRadius: BorderRadius.circular(14.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "提成合计",
            style: TextStyleConstant().white_28,
          ),
          SizedBox(
            height: 36.w,
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                "¥",
                style: TextStyleConstant().white_28,
              ),
              Text(
                "${AmountUtil.price2String((totalPercentageAmount) ?? 0)}",
                style: TextStyleConstant().white_46,
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget dataListItem({String title, String value, int money}) {
    return Container(
      decoration: BoxDecoration(border: Border(bottom: BorderSide(color: ColorConstant.e6e6, width: 1.px))),
      padding: EdgeInsets.symmetric(vertical: 32.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "${title == '' ? '--' : (title ?? '--')}",
            style: TextStyleConstant().normal_1_28,
          ),
          Text(
            "${value == '' ? '--' : (value ?? '--')}",
            style: TextStyleConstant().normal_1_28,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                "¥${AmountUtil.price2String((money) ?? 0)}",
                style: TextStyleConstant().normal_2_26,
              ),
//              Icon(Icons.arrow_forward_ios,
//                size: 26.sp,
//                color:ColorConstant.ff99,
//              ),
              Padding(
                padding: EdgeInsets.only(
                  left: 10.w,
                  right: 0.w,
                  top: 3.w,
                ),
                child: BaseImage(
                  'assets/image/arrow_right_icon_grey.png',
                  width: 13.w,
                  height: 26.w,
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget dataList() {
    return Container(
      child: Column(
        children: (acceptData ?? [])
            .map((str) => InkWell(
                  onTap: () async {
                    if (str["userId"] == '' || str["userId"] == null) {
                      toast("userId为空");
                      return;
                    }
                    await Navigator.pushNamed(context, InterestReportFormDetailsPage.pageName, arguments: {
                      "startTime": startTime,
                      "endTime": endTime,
                      "userId": str["userId"],
                    });
                  },
                  child: Container(
                    child: dataListItem(
                      title: str["post"],
                      value: str["userName"],
                      money: str["percentageAmount"],
                    ),
                  ),
                ))
            .toList(),
      ),
    );
  }

  Future<Result<List<dynamic>>> loadTask() async {
    return Result.value([]);
  }

  String dateTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  Future<Result<List<dynamic>>> refreshTask() async {
    var res = await api.statUserPercentageSumData(
      startTime: dateTime2String(startTime),
      endTime: dateTime2String(endTime),
    );
    if (res.successful()) {
      acceptData = [];
      ((res.data["userPercentageVoList"])).forEach((str) {
        if (str["userId"] != null && str["userId"] != '') {
          acceptData.add(str);
        }
      });
      totalPercentageAmount = (res.data["totalPercentageAmount"] ?? 0);
      setState(() {});
      return Result.value([1]);
    } else {
      toast(res.msg);
      return Result.value([]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 30.w,
      ),
      child: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(
                      top: 26.w,
                      bottom: 18.w,
                    ),
                    child: CalendarBar(
                      startDateTime: startTime,
                      endDateTime: endTime,
                      onDateTimeChanged: (List<DateTime> dateTime) {
                        startTime = dateTime[0];
                        endTime = dateTime[1];
                        loaderPullRefreshKey.currentState.refresh();
                      },
                      type: CalendarType.ymdhm,
                    ),
                  ),
                  titleBlock(),
                  SizedBox(
                    height: 10.w,
                  ),
                  Expanded(
                    child: LoaderPullRefresh<dynamic>(
                        key: loaderPullRefreshKey,
                        loadTask: loadTask,
                        refreshTask: refreshTask,
                        builder: (context) {
                          return Container(
                            child: SingleChildScrollView(
                              child: Column(
                                children: <Widget>[
                                  dataList(),
                                  SizedBox(
                                    height: 18.w,
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
